<template>
<div>
    <a-card
        style="width:100%"
        :tab-list="tabListNoTitle"
        :active-tab-key="noTitleKey"
        @tabChange="key => onTabChange(key, 'noTitleKey')"
        :headStyle="headStyle"
    >
        <!--    已登录用户信息    -->
        <div v-if="noTitleKey === 'login' && $store.getters.name !== ''" class="user-info">
            <a-avatar :size="90" icon="user" :src="$store.getters.avatar"/>
            <div class="user-info-hint">
                已登录{{ $store.getters.name }}账号
            </div>
            <div>
                <a-button type="primary" @click="$router.push('/user')">
                    进入个人中心
                </a-button>
            </div>
        </div>
        <!--    登录    -->
        <a-form-model
            v-if="noTitleKey === 'login' && $store.getters.name === ''"
            ref="loginForm"
            :rules="loginRules"
            :model="loginForm"
            id="login-form"
            class="login-form"
        >
            <a-form-model-item prop="username">
                <a-input
                    placeholder="请输入账号"
                    v-model="loginForm.username"
                >
                    <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
                </a-input>
            </a-form-model-item>
            <a-form-model-item prop="password">
                <a-input
                    type="password"
                    placeholder="请输入密码"
                    v-model="loginForm.password"
                >
                    <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
                </a-input>
            </a-form-model-item>
            <a-form-model-item prop="code" v-if="captchaOnOff">
                <a-input
                        v-model="loginForm.code"
                        placeholder="验证码"
                        @keyup.enter.native="handleLogin"
                        style="width: 63%"
                >
                    <a-icon slot="prefix" type="security-scan" style="color: rgba(0,0,0,.25)" />
                </a-input>
                <div class="login-code">
                    <img :src="codeUrl" @click="getCode" class="login-code-img"/>
                </div>
            </a-form-model-item>
            <a-form-model-item>
                <a-button type="primary"
                      html-type="submit"
                      class="login-form-button"
                      @click="userLogin()"
                      :loading="loadLogin">
                    登录
                </a-button>
            </a-form-model-item>
        </a-form-model>
        <!--    注册    -->
        <a-form-model
                ref="registForm"
                layout="horizontal"
                :model="registForm"
                v-else-if="noTitleKey === 'regist'"
                :rules="registRules"
                >
            <a-form-model-item prop="nickName">
                <a-input addon-before="姓名" placeholder="请输入真实姓名" v-model="registForm.nickName"/>
            </a-form-model-item>
            <a-form-model-item prop="username">
                <a-input addon-before="账号" placeholder="请输入学号或工号"  v-model="registForm.username"/>
            </a-form-model-item>
            <a-form-model-item prop="deptId">
                <a-select placeholder="请选择分党校" v-model="registForm.deptId">
                    <a-select-option v-for="deptItem in deptList" :value="deptItem.deptId" :key="deptItem.deptId">
                        {{deptItem.deptName}}
                    </a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item prop="password">
                <a-input-password addon-before="密码" placeholder="请输入密码"  v-model="registForm.password" />
            </a-form-model-item>
            <a-form-model-item prop="checkPassword">
                <a-input-password addon-before="确认密码" placeholder="请确认密码"  v-model="registForm.checkPassword" />
            </a-form-model-item>
            <a-form-model-item prop="email">
                <a-input addon-before="电子邮箱" placeholder="请输入电子邮箱"  v-model="registForm.email" />
            </a-form-model-item>
            <a-button type="primary" style="width: 100%;" @click="userRegister()">
                注册
            </a-button>
        </a-form-model>
    </a-card>
</div>
</template>

<script>
import { login, getCodeImg, register } from "@/api/login";
import { getPsDeptList } from "@/api/optionSelect"

export default {
  name: 'LoginRegistCard',
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.registForm.checkPassword !== '') {
          this.$refs.registForm.validateField('checkPass');
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else if (value !== this.registForm.password) {
        callback(new Error("两密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      codeUrl: "",
      // 验证码开关
      captchaOnOff: true,
      headStyle: {
        textAlign: "center"
      },
      loginRules: {
        username: [{required: true, message: '请输入账号', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}]
      },
      registRules: {
        nickName: [{required: true, message: '请输入真实姓名', trigger: 'blur'}],
        username: [{required: true, message: '请输入学号', trigger: 'blur'}],
        deptId: [{required: true, message: '请选择分党校', trigger: 'blur'}],
        checkPassword: [
          // {required: true, message: '请输入确认密码', trigger: 'blur'},
          {
            validator: validatePass2, trigger: 'change'
          }
        ],
        password: [
          // {required: true, message: '请输入密码', trigger: 'blur'},
          {
            validator: validatePass, trigger: 'change'
          }
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {required: true, message: '请输入邮箱', trigger: 'blur'},
        ],
      },
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: ""
      },
      loadLogin: false,
      registForm: {
        nickName: "",
        username: "",
        password: "",
        checkPassword: "",
        deptId: 200,
        email: ""
      },
      deptList: [
        {deptId: '-1', deptName: '---请选择分党校---'},
        {deptId: '200', deptName: '计算机'},
        {deptId: '201', deptName: '土木工程学院'},
        {deptId: '202', deptName: '教育学院'},
        {deptId: '203', deptName: '建筑与艺术设计学院'}
      ],
      // 登录注册tab
      tabList: [
        {
          key: 'tab1',
          // tab: 'tab1',
          scopedSlots: { tab: 'customRender' },
        },
        {
          key: 'tab2',
          tab: 'tab2',
        },
      ],
      tabListNoTitle: [
        {
          key: 'login',
          tab: '学员登录',
        },
        {
          key: 'regist',
          tab: '学员注册',
        },
      ],
      key: 'login',
      noTitleKey: 'login',
    }
  },
  beforeCreate() {
  },
  mounted() {
    this.getCode();
    this.initDeptList();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    userLogin() {
      console.log(this.loginForm.code);
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loadLogin = true;
          // login(this.loginForm.username, this.loginForm.password, this.loginForm.code, this.loginForm.uuid).then(res => {
          //   // 登录成功
          //   console.log(res);
          //   this.loadLogin = false;
          //
          // }).catch(err => {
          //   this.loadLogin = false;
          //   if (this.captchaOnOff) {
          //     this.getCode();
          //   }
          // })
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.loadLogin = false;
            this.$router.push({ path: '/user' }).catch(()=>{});
          }).catch(() => {
            this.loadLogin = false;
            if (this.captchaOnOff) {
              this.getCode();
            }
          });
        } else {
          this.loadLogin = false;
          return false;
        }
      });
    },
    userRegister() {
      this.$refs.registForm.validate(valid => {
            if (valid) {
              register(this.registForm).then(res => {
                console.log(res)
              }).catch(err => {
                console.log(err)
              })
            }
        }
      )
    },
    initDeptList() {
      getPsDeptList().then(res => {
        this.deptList = res.data;
      })
    },
    onTabChange(key, type) {
      console.log(key, type);
      this[type] = key;
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
        }
      });
    },
  }
}
</script>

<style>
.user-info {
    text-align: center;
}
.user-info-hint{
    font-size: 17px;
    margin-top: 15px;
    margin-bottom: 15px;
}
#login-form .login-form {
    max-width: 300px;
}
#login-form .login-form-forgot {
    float: right;
}
#login-form .login-form-button {
    width: 100%;
}
.login-code {
    width: 33%;
    height: 32px;
    float: right;
}
.login-code-img {
    width: 100%;
    height: 32px;
    display: inline-block;
    cursor: pointer;
    vertical-align: middle;
}
</style>
